<template>
  <div>
    <el-row style="margin-top: 20px">
      <el-col :span="18" :offset="3">
        <el-card shadow="always" class="box-card" style="height: 600px">
          <el-row style="margin-top: 20px">
            <el-col :span="4">
              <el-button
                size="small"
                type="primary"
                icon="el-icon-upload"
                plain
                round
                @click="uploadDialog=true">上传资料
              </el-button>
            </el-col>
            <el-col :span="4" :offset="15">
              <el-input
                placeholder="请输入资料名称"
                size="small"
                suffix-icon="el-icon-search"
                v-model="condition"
                @input="search"
                clearable>
              </el-input>
            </el-col>
          </el-row>
          <el-row style="margin-top: 10px">
            <el-table
              :data="tableData"
              max-height="420"
              style="width: 100%">
              <el-table-column
                label="资料名称"
                header-align="center"
                align="center"
                :show-overflow-tooltip="true"
                :render-header="renderHeader"
                width="210">
                <template slot-scope="scope">
                  <i class="el-icon-office-building"></i>
                  <span style="margin-left: 10px">{{ scope.row.resourceName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="资源类型"
                header-align="center"
                align="center"
                width="80">
                <template slot-scope="scope">
                  <i class="el-icon-tickets"></i>
                  <span style="margin-left: 10px">{{ scope.row.resourceType }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="资源大小"
                header-align="center"
                align="center"
                width="100">
                <template slot-scope="scope">
                  <i class="el-icon-pie-chart"></i>
                  <span style="margin-left: 10px">{{ sizeFormat(scope.row.resourceSize) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="资源地址"
                header-align="center"
                align="center"
                :show-overflow-tooltip="true"
                :render-header="renderHeader"
                width="280">
                <template slot-scope="scope">
                  <i class="el-icon-position"></i>
                  <span style="margin-left: 10px">{{ scope.row.resourceUrl }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="创建时间"
                header-align="center"
                align="center"
                width="185">
                <template slot-scope="scope">
                  <i class="el-icon-time"></i>
                  <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                width="250"
                align="center" label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="distribution(scope.$index, scope.row)">分配
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="download(scope.$index, scope.row)">下载
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="rename(scope.$index, scope.row)">重命名
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDelete(scope.$index, scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row style="margin-top: 30px">
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              layout="total, prev,pager, next, jumper"
              :total="total"
              :page-size="limit">
            </el-pagination>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      title="资源上传"
      :visible.sync="uploadDialog"
      @close="cancelUpload"
      width="30%"
      center>
      <div style="text-align: center">
        <el-upload
          class="upload-demo"
          drag
          ref="upload"
          :auto-upload="true"
          :on-success="handleSuccess"
          :on-error="handleError"
          :headers="{Authorization:this.$store.state.authorization}"
          action="/api/common/resource"
          list-type="text"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__text" style="margin-top: 10px">上传文件大小不超过500MB</div>
        </el-upload>
      </div>
    </el-dialog>

    <el-dialog :before-close="cancel" title="课程列表" :visible.sync="resourceDialog" width="400px" center>
      <el-row>
        <el-col :span="10" :offset="6">
          <el-select clearable filterable v-model="resourceCourse.courseId" placeholder="请选择课程" style="width:100%">
            <el-option v-for="(item,index) in list" :key="index" :label="item.courseName"
                       :value="item.courseId"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="complete">完 成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Resource',
  data () {
    return {
      resourceDialog: false,
      list: [],
      resourceCourse: {
        courseId: undefined,
        resourceId: undefined,
      },
      uploadDialog: false,
      tableData: [],
      condition: '',
      total: 0,
      limit: 6,
      currentPage: 1,
    }
  },
  methods: {
    sizeFormat (limit) {
      let size = ''
      if (limit < 0.1 * 1024) {                            //小于0.1KB，则转化成B
        size = limit.toFixed(2) + 'B'
      } else if (limit < 0.1 * 1024 * 1024) {            //小于0.1MB，则转化成KB
        size = (limit / 1024).toFixed(2) + 'KB'
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {        //小于0.1GB，则转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
      } else {                                            //其他转化成GB
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }
      let sizeStr = size + ''                        //转成字符串
      let index = sizeStr.indexOf('.')                    //获取小数点处的索引
      let dou = sizeStr.substr(index + 1, 2)            //获取小数点后两位的值
      if (dou == '00') {                                //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      }
      return size
    },
    handleDelete (index, row) {
      this.$http({
        url: '/api/resource/' + row.resourceId,
        method: 'delete'
      }).then(res => {
        if (res.data.code === 4040) {
          this.$message({
            type: 'success',
            message: '删除成功!',
            duration: 1000
          })
          this.init()
        } else {
          this.$message({
            type: 'warning',
            message: '删除失败,请检查文件是否被引用!',
            duration: 1000
          })
        }
      })
    },
    search () {
      this.init()
    },
    init () {

      this.$http({
        url: '/api/resource/list',
        method: 'get',
        params: {
          condition: this.condition,
          page: this.currentPage,
          limit: this.limit
        },
      }).then(res => {
        this.total = res.data.result.total
        this.tableData = res.data.result.records
      })

      this.$http({
        url: '/api/course/list',
        method: 'get',
      }).then(res => {
        this.list = res.data.result
      })

    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.init()
    },
    cancelUpload () {
      this.$refs.upload.clearFiles()
    },
    handleSuccess () {
      this.$message({
        type: 'success',
        message: '上传成功!',
        duration: 1500,
      })
      this.init()
    },
    handleError () {
      this.$message({
        type: 'error',
        message: '上传失败!',
        duration: 1500,
      })
    },
    renderHeader (h, data) {
      return h('span', [
        h(
          'el-tooltip',
          {
            attrs: {
              class: 'item',
              effect: 'dark',
              content: data.column.label,
              placement: 'top',
            },
          },
          [h('span', data.column.label)]
        ),
      ])
    },
    rename (index, row) {
      this.$prompt('请输入想要更改的文件名', '修改文件名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.$http({
          url: '/api/resource/rename',
          method: 'post',
          data: {
            resourceId: row.resourceId,
            resourceName: value
          },
        }).then((res) => {
          if (res.data.code === 4040) {
            this.$message({
              type: 'success',
              message: '文件重命名成功！',
              duration: 1500,
            })
            this.init()
          } else {
            this.$message({
              type: 'error',
              message: '文件重命名失败！',
              duration: 2000,
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消更新昵称',
          duration: 2000,
        })
      })
    },
    download (index, row) {
      window.location.href = 'http://localhost/common/download/' + row.resourceId
    },
    distribution (index, row) {
      this.resourceCourse.resourceId = row.resourceId
      this.resourceDialog = true
    },
    cancel () {
      this.resourceCourse = {
        courseId: undefined,
        resourceId: undefined,
      }
      this.resourceDialog = false
    },
    complete () {
      this.$http({
        url: '/api/resourceCourse',
        method: 'post',
        data: {
          courseId: this.resourceCourse.courseId,
          resourceId: this.resourceCourse.resourceId
        },
      }).then((res) => {
        if (res.data.code === 2000) {
          this.$message({
            type: 'success',
            message: '文件分配成功！',
            duration: 1500,
          })
          this.cancel()
        } else {
          this.$message({
            type: 'error',
            message: '文件分配失败！',
            duration: 2000,
          })
        }
      })
    }
  },
  created () {
    this.init()
  }
}
</script>

<style scoped>
.el-table .cell {
  word-break: keep-all !important;
  white-space: nowrap !important;
}

</style>
